package com.aqie.easy.binaryTree;

import com.aqie.easy.structure.TreeNode;

import java.util.LinkedList;
import java.util.List;

/**
 * 637 二叉树的层平均值
 * 层序遍历二叉树
 * todo
 */
public class AverageOfLevels {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ans = new LinkedList<>();
        List<TreeNode> treeNodes = new LinkedList<>();
        treeNodes.add(root);
        while (!treeNodes.isEmpty()){
            int size = treeNodes.size();
            double levelSum = 0;
            for (int i = 0; i < size; i++){
                TreeNode node = treeNodes.remove(0);
                levelSum += node.val;
                if (node.left != null) treeNodes.add(node.left);
                if (node.right != null) treeNodes.add(node.right);
            }
            ans.add(levelSum / size);
        }
        return ans;
    }

}
